package initialize

import (
	"context"
	"errors"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"

	"ginmt/handlers"
	"ginmt/pkg"

	"github.com/gin-gonic/gin"
)

type App struct {
	srv    *http.Server
	AppCtx *pkg.AppCtx
}

func NewApp(srv *http.Server, ctx *pkg.AppCtx) *App {
	return &App{srv: srv, AppCtx: ctx}
}

func (a *App) Run() {
	a.initRouter()
	a.start()
}

func (a *App) start() {
	go func() {
		// 服务连接
		if err := a.srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("listen: %s\n", err)
		}
	}()
	// 等待中断信号以优雅地关闭服务器（设置 5 秒的超时时间）
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit
	log.Println("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := a.srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
	log.Println("Server exiting")
	os.Exit(0)
}

func (a *App) initRouter() {
	if r, ok := a.srv.Handler.(*gin.Engine); ok {
		r.GET("/product", handlers.Product(a.AppCtx))
		r.GET("/regional/city", handlers.City(a.AppCtx))
		r.GET("/regional/city/value", handlers.CityValue(a.AppCtx))
		r.GET("/product/link", handlers.Link(a.AppCtx))
		r.POST("/wechat/jsconfig", handlers.WechatJsConfig(a.AppCtx))
	} else {
		panic(errors.New("gin handler not registered"))
	}
}
